package com.neueedu.android;


import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.DatabaseErrorHandler;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.neueedu.android.ticket.TicketActivity1;
import com.neueedu.android.ticket.TicketActivity2;


/**
 * A simple {@link Fragment} subclass.
 */
public class TicketFragment extends Fragment implements View.OnClickListener {


    private TextView tvTicketStationFrom;
    private TextView tvTicketStationTo;
    private TextView tvTicketHistory1;
    private TextView tvTicketHistory2;
    private ImageView imgTicketExchange;
    private Button btnTicketQuery;
    int version  = 3;

    public TicketFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_ticket, container, false);
    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        tvTicketStationFrom = getActivity().findViewById(R.id.tvTicketStationFrom);
        imgTicketExchange = getActivity().findViewById(R.id.imgTicketExchange);
        tvTicketStationTo = getActivity().findViewById(R.id.tvTicketStationTo);
        btnTicketQuery = getActivity().findViewById(R.id.btnTicketQuery);
        tvTicketHistory1 = getActivity().findViewById(R.id.tvTicketHistory1);
        tvTicketHistory2 = getActivity().findViewById(R.id.tvTicketHistory2);


        tvTicketStationFrom.setOnClickListener(this);
        tvTicketStationTo.setOnClickListener(this);


        imgTicketExchange.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TranslateAnimation translateAnimation = new TranslateAnimation(0,300,0,0);
                translateAnimation.setDuration(1500);  //持续2秒
                translateAnimation.setInterpolator(new LinearInterpolator()); //匀速





                TranslateAnimation translateAnimation2 = new TranslateAnimation(0,-300,0,0);
                translateAnimation2.setDuration(1500);  //持续2秒
                translateAnimation2.setInterpolator(new LinearInterpolator()); //匀速
                translateAnimation2.setAnimationListener(new Animation.AnimationListener() {
                    @Override
                    public void onAnimationStart(Animation animation) {

                    }

                    @Override
                    public void onAnimationEnd(Animation animation) {
                        CharSequence fromText = tvTicketStationFrom.getText();
                        CharSequence toText = tvTicketStationTo.getText();
                        tvTicketStationTo.setText(fromText);
                        tvTicketStationFrom.setText(toText);
                    }

                    @Override
                    public void onAnimationRepeat(Animation animation) {

                    }
                });


                tvTicketStationFrom.startAnimation(translateAnimation);
                tvTicketStationTo.startAnimation(translateAnimation2);
            }
        });





        btnTicketQuery.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //记录出发和到达车站
                logStationHistitory();


                //查询
                Intent intent = new Intent(getActivity(), TicketActivity2.class);
                intent.putExtra("from",tvTicketStationFrom.getText());
                intent.putExtra("to",tvTicketStationTo.getText());
                startActivity(intent);


            }
        });

    }


    @Override
    public void onResume() {
        super.onResume();
        loadStationHistory();
    }

    //通过获取 SQLite数据库中的历史 显示到 界面中
    private void loadStationHistory() {
        MySQLiteOpenHelper sqLiteOpenHelper = new MySQLiteOpenHelper(version);
        SQLiteDatabase db = sqLiteOpenHelper.getReadableDatabase();


        Cursor cursor = db.rawQuery("select id,fromto from history  order by  id desc limit 2  ", null);

        //第一行
        if(cursor.moveToNext()){
            String fromto1 = cursor.getString(cursor.getColumnIndex("fromto"));
            tvTicketHistory1.setText(fromto1);
        }
        if(cursor.moveToNext()){
            String fromto2 = cursor.getString(cursor.getColumnIndex("fromto"));
            tvTicketHistory2.setText(fromto2);
        }

    }

    private void logStationHistitory() {


        //使用SQLite数据库记录

        MySQLiteOpenHelper sqLiteOpenHelper = new MySQLiteOpenHelper(version);
        SQLiteDatabase db = sqLiteOpenHelper.getWritableDatabase();


        ContentValues contentValues = new ContentValues();
        String fromto = tvTicketStationFrom.getText().toString()+"----"+tvTicketStationTo.getText().toString();
        contentValues.put("id",System.currentTimeMillis());
        contentValues.put("fromto", fromto  );

//        db.execSQL("insert into history (id,fromto) values(?,?)",System.currentTimeMillis(),fromto);
        db.insert("history",null,contentValues);
        db.close();


    }



    class MySQLiteOpenHelper extends  SQLiteOpenHelper{

        public MySQLiteOpenHelper( int version) {
            super(getActivity(), "station_history", null, version);
        }


        /**
         * 第一次 调用数据库open的时候 执行
         * @param db
         */
        @Override
        public void onCreate(SQLiteDatabase db) {
            db.execSQL("CREATE TABLE history ( id  INTEGER, fromto TEXT )");
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

            //判断版本的 更新
//            db.execSQL("升级 添加 字段、表、删除字段  ");

            Toast.makeText(getActivity(), "触发升级--new Version:"+newVersion, Toast.LENGTH_LONG).show();
        }

//        public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
//            throw new SQLiteException("Can't downgrade database from version " +
//                    oldVersion + " to " + newVersion);
//        }
    }




    @Override
    public void onClick(View v) {

        //启动Activity
        Intent intent = new Intent(getActivity(), TicketActivity1.class);
        startActivityForResult(intent  ,v.getId());

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if(data != null){
            String stationName = data.getStringExtra("stationName");

            if(requestCode == R.id.tvTicketStationFrom){
                tvTicketStationFrom.setText(stationName);

            }else if(requestCode == R.id.tvTicketStationTo){
                tvTicketStationTo.setText(stationName);
            }
        }



    }
}
